import { DatabaseEnvStore } from "@/modules/dev-env/database/common/database-env-store.ts";
import type { LocalVersionItem } from "@/modules/dev-env/common/types.ts";
import type { BaseEnvMirror } from "@/modules/dev-env/mirror/mirror.ts";
import { MysqlHistoryMirror, MysqlLatestMirror } from "./mysql-mirror.ts";
import path from "@/framework/util/path.ts";
import type { EnvTableAction } from "@/modules/dev-env/store/types.ts";
import { openInTerminal } from "@/util/system-utils2.ts";
import MysqlSettings from "./mysql-settings.vue";
import { showMessageAndPrint } from "@/framework/util/log.ts";
import { message } from "ant-design-vue";

export class MysqlEnvStore extends DatabaseEnvStore<MysqlEnvStore> {
  constructor() {
    super("mysql");
    this.icon = "icon-mysql";

    this.settingsComponent = MysqlSettings;

    this.pageConfig = {
      showCurrentAction: false,
    };

    this.tableActions = this._tableActions();
  }

  private _tableActions(): EnvTableAction[] {
    return [
      {
        key: "config-install",
        icon: "icon-setting",
        name: "配置/安装",
        onClick: version => (this.proxy.selectedItem = version),
      },
      {
        key: "run-mysql-configurator",
        icon: "icon-mysql",
        name: "MySQL Configurator",
        onClick: v => this._openMysqlConfigurator(v),
      },
      {
        key: "open-in-shell",
        icon: "icon-terminal",
        name: "在终端打开",
        onClick: version => openInTerminal(version.installPath, { subPath: ["bin"] }),
      },
      {
        key: "mysqldump",
        icon: "icon-dump",
        name: "mysqldump(开发中)",
        onClick: version => void 0,
        disabled: true,
      },
    ];
  }

  /**
   * 打开新版MySQL官方的配置工具
   * @param version
   * @private
   */
  private async _openMysqlConfigurator(version: LocalVersionItem) {
    const exeFile = path.join(version.installPath, "bin/mysql_configurator.exe");
    if (await native.fs.exists1(exeFile)) {
      await native.cp.execCmdSudo(exeFile).catch(showMessageAndPrint);
    } else {
      message.error("该版本不支持MySQL Configurator");
    }
  }

  protected getMirrors0(): BaseEnvMirror[] {
    return [new MysqlLatestMirror(), new MysqlHistoryMirror()];
  }

  protected async getVersionInfo(versionDir: string): Promise<LocalVersionItem | undefined> {
    const mysqld = path.join(versionDir, "bin/mysqld.exe");
    if (!(await native.fs.exists(mysqld))) {
      return undefined;
    }

    const folderName = path.basename(versionDir);
    const [, version, _] = folderName.split("-");
    return { version: version, installPath: versionDir };
  }
}
